<template>
  <div>
    <Logo></Logo>
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="userName"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <van-field
        v-model="repassword"
        type="password"
        name="repwd"
        label="密码"
        placeholder="确认密码"
        :rules="[{ required: true, message: '请重复填写密码' }]"
      />
      <div style="margin: 16px">
        <van-button style="width: 100%" type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
    <router-link to="/login">已有账号？需要登录</router-link>
  </div>
</template>

<script>
import { Toast } from 'vant';
import Logo from '../components/Logo.vue';
import { RegAPI } from '../service/user';
import { setToken } from '../tools/util';

export default {
  name: 'VueYimutianResg',

  data() {
    return {
      username: '',
      password: '',
      repassword: '',
    };
  },
  methods: {
    async onSubmit(values) {
      console.log('submit', values);
      if (this.password === this.repassword) {
        const res = await RegAPI({
          userName: values.userName,
          password: values.password,
        });
        console.log(res);
        if (res.data.code === 1) {
          Toast.success('注册成功');
          setToken(res.data.data);
          this.$router.replace({
            name: 'VueYimutianLogin',
          });
        } else {
          Toast.fail('用户信息已经存在');
        }
      } else {
        Toast.fail('两次输入密码不一致');
      }
    },
    onConfirm(date) {
      this.value = `${date.getMonth() + 1}/${date.getDate()}`;
      this.showCalendar = false;
    },
  },
  components: {
    Logo,
  },
};
</script>

<style lang="scss" scoped>
</style>
